#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require 'set'
require_relative '../defconfig.rb'

names = Set.new %w[
  SCHED_HOST
  SCHED_PORT
  REDIS_HOST
  REDIS_PORT
  ES_HOST
  ES_PORT
  ES_USER
  ES_PASSWORD
  OS_HTTP_HOST
  OS_HTTP_PORT
  INITRD_HTTP_HOST
  INITRD_HTTP_PORT
  TASKQUEUE_PORT
  TASKQUEUE_HOST
  GIT_SERVER
  MASTER_FLUENTD_HOST
  MASTER_FLUENTD_PORT
  SSHR_PORT
  SSHR_PORT_BASE
  SSHR_PORT_LEN
  SRV_HTTP_CCI_HOST
  SRV_HTTP_CCI_PORT
  lab
]

defaults = relevant_defaults(names)
defaults['SSHR_PORT'] ||= 5051
defaults['SSHR_PORT_BASE'] ||= 21000
defaults['SSHR_PORT_LEN'] ||= 2000
defaults['SCHED_PORT'] ||= '3000'
defaults['SCHED_HOST'] ||= '172.17.0.1'
defaults['MASTER_FLUENTD_PORT'] ||= '24224'
defaults['SRV_HTTP_CCI_PORT'] ||= '11307'

service_authentication = relevant_service_authentication(names)
defaults.merge!(service_authentication)

env = docker_env(defaults)

CCI_REPOS = ENV['CCI_REPOS'] || '/c'
DEFAULT_LKP = "#{CCI_REPOS}/lkp-tests"
DEFAULT_CCI = "#{CCI_REPOS}/compass-ci"
LAB = defaults['lab'] || 'z9'
SCHED_PORT = defaults['SCHED_PORT']
SCHED_HOST = defaults['SCHED_HOST']

docker_rm "s001-alpine-#{SCHED_PORT}"

bind_list = []
[SCHED_HOST, '172.17.0.1'].uniq.each do |ip|
  bind_list << '-p'
  bind_list << "#{ip}:#{SCHED_PORT}:#{SCHED_PORT}"
end

cmd = %W[
  docker run
  --restart=always
  --name s001-alpine-#{SCHED_PORT}
  -it
  -u 1090:1090
] + bind_list + env + %W[
  -e CCI_REPOS=#{CCI_REPOS}
  -e LKP_SRC=#{DEFAULT_LKP}
  -e CCI_SRC=#{DEFAULT_CCI}
  -e NODE_PORT=#{SCHED_PORT}
  -v #{ENV['LKP_SRC']}:#{DEFAULT_LKP}
  -v #{ENV['CCI_SRC']}:#{DEFAULT_CCI}
  -v #{CCI_REPOS}/lab-#{LAB}:#{CCI_REPOS}/lab-#{LAB}
  -v /srv/cci/scheduler/alpine:/srv/cci/scheduler
  -v /srv/tmp/public:/c/cci/scheduler/public
  -v /etc/compass-ci:/etc/compass-ci:ro
  -v /etc/localtime:/etc/localtime:ro
  -v /srv/result:/srv/result
  -v /srv/initrd:/srv/initrd:ro
  -v /srv/upload-files:/srv/upload-files:rw
  -v /srv/os:/srv/os:ro
  --log-opt mode=non-blocking
  --log-opt max-buffer-size=4m
  --log-opt tag=scheduler-#{SCHED_PORT}
  sch-ruby-a:v0.00d-#{SCHED_PORT}
]

cmd += ['sh', '-c', 'umask 002 && ./scheduler']

system(*cmd)
